package br.com.tecnoria.controllers
{
	import br.com.tecnoria.vo.ProductVO;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;
	
	import org.swizframework.utils.services.ServiceHelper;
	
	public class ProductController
	{
		[Inject("productRemote")]
		public var remote:RemoteObject;
		
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		[Bindable]
		public var dataprovider:ArrayCollection;
		
		[Bindable]
		public var product:ProductVO;
		
		/**
		 * Call Function
		 */
		
		[EventHandler(event="ProductEvent.SAVE", properties="product")]
		public function saveProduct(product:ProductVO):void
		{
			serviceHelper.executeServiceCall(remote.saveProduct(product), onSaveProduct, onFault);
		}
		
		[EventHandler(event="ProductEvent.LIST")]
		public function listProduct():void
		{
			serviceHelper.executeServiceCall(remote.listProduct(), onListProduct, onFault);
		}
		
		[EventHandler(event="ProductEvent.UPDATE", properties="product")]
		public function updateProduct(product:ProductVO):void
		{
			serviceHelper.executeServiceCall(remote.updateProduct(product), onUpdateProduct, onFault);
		}
		
		[EventHandler(event="ProductEvent.DELETE", properties="product")]
		public function deleteProduct(product:ProductVO):void
		{
			serviceHelper.executeServiceCall(remote.deleteProduct(product), onDeleteProduct, onFault);
		}
		
		[EventHandler(event="ProductEvent.SEARCH", properties="product")]
		public function searchProduct(product:ProductVO):void
		{
			serviceHelper.executeServiceCall(remote.searchProduct(product.name), onListProduct, onFault);
		}
		
		
		/**
		 * Result Function
		 */
		
		public function onSaveProduct(result:ResultEvent):void
		{
			Alert.show("Produto salvo com sucesso!");
			product = new ProductVO(result.result);
		}
		
		public function onListProduct(result:ResultEvent):void
		{
			dataprovider = new ArrayCollection(result.result as Array);
		}
		
		public function onUpdateProduct(result:ResultEvent):void
		{
			Alert.show("Produto alterado com sucesso!");
			product = new ProductVO(result.result);
		}
		
		public function onDeleteProduct(result:ResultEvent):void
		{
			Alert.show("Produto removido com sucesso!");
			listProduct();
		}
		
		/**
		 * Fault Function
		 */
		
		public function onFault(result:FaultEvent):void
		{
			Alert.show(result.fault.toString(), "Erro");
		}
	}
}